﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Ceremony.API.Model;
using Ceremony.API.ParameterModel;
using Ceremony.API.ViewModel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace Ceremony.API.Controllers
{
    [Route("api/v1/ceremony")]
    [ApiController]
    public class PersonalController : ControllerBase
    {
        private readonly ILogger<PersonalController> _logger;
        private readonly CeremonyContext _context;
        private readonly CeremonySettings _settings;
        private readonly HttpClient _client;
        public PersonalController(ILogger<PersonalController> logger, 
            CeremonyContext context, 
            IOptionsSnapshot<CeremonySettings> settings)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _context = context ?? throw new ArgumentNullException(nameof(context));
            _settings = settings.Value ?? throw new ArgumentNullException(nameof(settings));
            if (_client == null)
            {
                _client = new HttpClient();
            }
        }
        /// <summary>
        /// 创建授权码
        /// </summary>
        /// <param name="authorizeCode"></param>
        /// <returns></returns>
        [Route("user/authorizecode")]
        [HttpPost]
        [ProducesResponseType((int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.BadRequest)]
        public async Task<IActionResult> CreateAuthorizeCode([FromBody]CreateAuthorizeCode authorizeCode)
        {
            var codes = _context.Authorizes.Where(t => t.IsEnable == false);
            Random random = new Random();
            for(int i = 0;i< authorizeCode.Num; i++)
            {
               string code = "";
                while (true)
                {
                    int randomNum = random.Next(10000, 999999);
                    code = randomNum.ToString();
                    if (code.Length < 6)
                    {
                        code = code.PadLeft(6, '0');
                    }
                    if(!codes.Any(t => t.Code == code))
                    {
                       await _context.Authorizes.AddAsync(new Model.Authorize(code));
                       break;
                    }
                }
            }
            var result = await _context.SaveChangesAsync();
            string resultStr = result > 0 ? "succeed" : "failed";
            _logger.LogInformation("-----Create Authorize {Result}",resultStr);
            if (result > 0)
            {
                return Ok();
            }
            else
            {
                return BadRequest();
            }
        }
        /// <summary>
        /// 获取授权码
        /// </summary>
        /// <returns></returns>
        [Route("user/authorizecodes")]
        [HttpGet]
        [ProducesResponseType((int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.BadRequest)]
        public ActionResult<IEnumerable<Model.Authorize>> GetAuthorizes()
        {
            var codes = _context.Authorizes.Where(t => t.IsEnable == false);
            return Ok(codes);
        }
    }
}